package com.dayuanit.dy15.ebook.bookshop.controller;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.OutputStream;

@Controller
@Slf4j
public class PictureController {

    //@Slf4j  可以不写 用注解
//    private static final Logger logger = LoggerFactory.getLogger(PictureController.class);

    @Value("${ebook.picture.path}")
    private String picturePath;

    //http://ip:port/images/xxxxx.jpg
    @RequestMapping("/images/{pictureName}")
    public void showPicture(@PathVariable("pictureName") String pictureName, HttpServletResponse response) {
        response.setContentType("image/jpeg");
        try (FileInputStream fis = new FileInputStream(picturePath + pictureName);) {
            OutputStream os = response.getOutputStream();
            byte[] buff = new byte[2048];
            int length = -1;
            while (-1 != (length = fis.read(buff))) {
                os.write(buff, 0, length);
                os.flush();
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    //http://ip:port/images2?pictureName=xxxxx.jpg
    @RequestMapping("/images2")
    public void showPicture2(String pictureName, HttpServletResponse response) {

    }
}
